namespace Ultimate.Controls
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;

	using Ultimate.DAL.CollectionClasses;
	using Ultimate.DAL;
	using Ultimate.DAL.HelperClasses;
	using Ultimate.DAL.EntityClasses;
	using Ultimate.DAL.FactoryClasses;
	using SD.LLBLGen.Pro.ORMSupportClasses;
    using System.Web.Security;

    using CommunityServer.Components;
	/// <summary>
	///		Summary description for Menu.
	/// </summary>
	public class PlayerPanel : System.Web.UI.UserControl
	{
		protected System.Web.UI.WebControls.Literal Content;
		

      
		private void Page_Load(object sender, System.EventArgs e)
		{
			if(!this.IsPostBack && Context.User.Identity.IsAuthenticated)
			{
				BindData();
			}
		}

        private void BindData()
        {
            string tmp = "";


            string userName;
            string message;

            MembershipUser mu = Membership.GetUser();
            Guid userID = (Guid)mu.ProviderUserKey;
            userName = "Welcome " + mu.UserName;

            DAL.TypedListClasses.PlayerTeamLeagueTypedList ptl = new DAL.TypedListClasses.PlayerTeamLeagueTypedList();
            PredicateExpression A = new PredicateExpression();
            A.Add(PredicateFactory.CompareValue(PlayerFieldIndex.UserID, ComparisonOperator.Equal, userID));
            A.Add(PredicateFactory.CompareValue(LeagueFieldIndex.Active, ComparisonOperator.Equal, true));
            ISortExpression sorter = new SortExpression(SortClauseFactory.Create(TeamFieldIndex.TeamName, SortOperator.Ascending));
            ptl.Fill(0, sorter, false, A);
            message = "<div class=\"CommonSidebarContentItem\">Your Teams";
            message += "<span style=padding-left:70px;>&nbsp;</span>" + CreateScheduleLinks(Ultimate.Download.ScheduleType.Individual, -1) + "</div><ul>";

            bool isCaptain = false;
            foreach (DAL.TypedListClasses.PlayerTeamLeagueRow ptlr in ptl.Rows)
            {
                //list the team name with a link and the ical schedule
                message += "<li><a href=\"" + this.ResolveUrl("~/RegistrationSystem/Team/Editteam.aspx?teamID=" + ptlr.TeamID.ToString()) + "\">" + ptlr.TeamName + "</a>&nbsp;&nbsp;";
                message += CreateScheduleLinks(Ultimate.Download.ScheduleType.Team, ptlr.TeamID) + "</br>";

                //get the next game and show that
                GameEntity ge = GetNextGame(ptlr.TeamID);
                if (ge != null)
                {
                    message += "Next Game: " + ge.GameDay.ToShortDateString() + "<br />";
                    message += ge.Field.FieldName;
                }
                message+="</li>";

                if (ptlr.RoleID == 1)
                {
                    isCaptain = true;
                }
            }
            message += "</ul>";

            if (isCaptain)
            {
                string url = ResolveUrl("../League/ViewGames.aspx");
                message += "<div class=\"CommonSidebarContentItem\"><a href='" + url + "'>Score Entry</a></div>";
            }

            tmp = @"
                    <div class=""CommonSidebarArea"">
						<h4 class=""CommonSidebarHeader"">Your League Infoz" + @"</h4>
						<div class=""CommonSidebarContent"">"
                           + message + @"
                        </div>
                    </div>";
            Content.Text = tmp;


        }

        /// <summary>
        /// Creates the html for the calendar schedule links.
        /// </summary>
        /// <returns></returns>
        private string CreateScheduleLinks(Ultimate.Download.ScheduleType scheduleType, int id)
        {
            string linksTemplate = "<span class='ical'><a href='/RegistrationSystem/download/schedule.aspx?{0}'><img src='/RegistrationSystem/Images/calendar.png' alt='iCal' /></a></span>";

            //set the query string schedule type
            int schedType = (int)scheduleType;
            string queryStr = "stype=" + schedType.ToString();
            //set the query string schedule format
            int schedFormat = (int)Ultimate.Download.ScheduleFormat.iCal;
            queryStr += "&sFormat=" + schedFormat.ToString();
            //set the query string team id if it exists.
            if (id != -1)
                queryStr += "&id=" + id.ToString();
            
            return string.Format(linksTemplate, queryStr);

        }
        private GameEntity  GetNextGame(int teamID)
        {
            
            GameCollection gec = new  GameCollection();
            IRelationCollection relations = new RelationCollection();

            relations.Add(GameEntity.Relations.TeamEntityUsingAwayTeamID);
            //relations.Add(GameEntity.Relations.TeamEntityUsingHomeTeamID,);

            PredicateExpression A = new PredicateExpression();
            A.Add(PredicateFactory.CompareValue(GameFieldIndex.GameDay, ComparisonOperator.GreaterEqual , DateTime.Today));

            PredicateExpression teamFilter = new PredicateExpression();
            teamFilter.Add(PredicateFactory.CompareValue(GameFieldIndex.AwayTeamID, ComparisonOperator.Equal, teamID));
            teamFilter.AddWithOr(PredicateFactory.CompareValue(GameFieldIndex.HomeTeamID, ComparisonOperator.Equal, teamID));

            A.AddWithAnd(teamFilter);

            ISortExpression sorter = new SortExpression(SortClauseFactory.Create(GameFieldIndex.GameDay , SortOperator.Ascending));
            gec.GetMulti(A, 1, sorter, relations);
            if (gec.Items.Count > 0)
                return (GameEntity)gec.Items[0];
            return null;
        }
		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion
	}
}
